<script lang="ts" setup>
import { ArticleStoreType } from "@/typing";
import { useRouter } from "vue-router";
import 'vant/es/toast/style';
import { Toast } from "vant";
import { ref, watch, toRefs } from "vue";
import { storeToRefs } from "pinia";
import { localStoriesStore, userLocalStoriesStore } from "../../store";

const router = useRouter();

const localStore = localStoriesStore();
const { refreshArticleCollectStore, selectArticleCollectId } = localStore;

const userStore = userLocalStoriesStore();
const { isLogin } = storeToRefs(userStore);
const { getMyUserStatus } = userStore;

let toggleCollect = ref<boolean>(false);
let collect = ref<string>();
let isCollect = ref<boolean>();

const props = defineProps<{
    obj: ArticleStoreType
}>()

isLogin.value = getMyUserStatus();

const { obj } = toRefs(props)

isCollect.value = selectArticleCollectId(obj.value.id);

watch(() => isLogin.value, () => {
    isCollect.value = selectArticleCollectId(obj.value.id);
    isCollectShow(isLogin.value)
})

watch(() => obj.value, () => {
    isCollect.value = selectArticleCollectId(obj.value.id);
    isCollectShow(isLogin.value)
})

isCollectShow(isLogin.value)

// 是否已经收藏
function isCollectShow(isLogin: boolean) {
    if (!isLogin) {
        isNotCollectFunc();
    } else {
        if (isCollect.value) {
            isCollectFunc();
        }
        else {
            isNotCollectFunc();
        }
    }
}

// 点击收藏或取消收藏
function updateCollect() {
    if (!isLogin.value) {
        router.push({
            name: 'login',
        })
    } else {
        if (toggleCollect.value) {
            isNotCollectFunc();
            refreshArticleCollectStore(obj.value);
            Toast('取消收藏');
        }
        else {
            isCollectFunc();
            refreshArticleCollectStore(obj.value);
            Toast('收藏成功');
        }
    }
}

// 收藏的样式
function isCollectFunc() {
    toggleCollect.value = true;
    collect.value = require("../../assets/card/stow_selected.png");
}

// 不收藏的样式
function isNotCollectFunc() {
    toggleCollect.value = false;
    collect.value = require("../../assets/card/stow_default.png");
}

</script>

<template>
    <div class="flex items-center">
        <img class="w-10 h-10" @click="updateCollect()" :src="collect || require('../../assets/card/stow_default.png')"
            alt="share">
    </div>
</template>